package com.xcity.logupload.util;

import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

public class PropertiesLoader {

	public static Properties load(String resource) {
		InputStream input = null;
		try {
			input = IOUtils.getResource(resource);
			if (input == null) {
				return null;
			}
			Properties prop = new Properties();
			prop.load(input);
			return prop;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(input);
		}
		return null;
	}
	
	public static <T> T load(String resource, Class<T> type) {
		try {
			Properties prop = load(resource);
			if (prop == null) {
				return null;
			}
			Set<Entry<Object, Object>> set = prop.entrySet();
			T instance = type.newInstance();
			for (Entry<Object, Object> entry : set) {
				String key = String.valueOf(entry.getKey());
				Object value = entry.getValue();
				ReflectUtils.setField(type, instance, key, value);
			}
			return instance;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
